<?php
namespace app\cloud\controller;
use think\Controller;
use think\Db;
use Memcached;
use EasyWeChat\Foundation\Application;
use Doctrine\Common\Cache\MemcachedCache;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\Transfer;
class Openplatform extends Controller
{

	//公共配置参数
    private function initialize()
    {

        $options = [
            // 曼联共享充电宝
            'open_platform' => config('wechat.open_platform'), 
        ];
        if(config('wechatchche')){
        	$memcached = new Memcached();
	        $memcached->addServer(config('wechatchche.host'), config('wechatchche.port'));
	        $cacheDriver = new MemcachedCache();
	        $cacheDriver->setMemcached($memcached);
        	$options['cache']=$cacheDriver;
        }
        $app = new Application($options);
        $openPlatform = $app->open_platform;
        return  $openPlatform;

    }

    //获取公众号或小程序授权
    public function authorization(){
        $openPlatform = $this -> initialize();

        $code = $openPlatform->pre_auth->getCode();
        // 直接跳转
        $response = $openPlatform->pre_auth->redirect(config('website').'/cloud/Openplatform/callback');
        // 获取跳转的 URL
        $TargetUrl =  $response->getTargetUrl();
       //var_dump($TargetUrl);
	   $this->assign('url',$TargetUrl);
	   return $this->fetch();

    }
    //获取component_access_token
    public function component_access_token(){

    	$openPlatform = $this -> initialize();

        $accessToken = $openPlatform->access_token->getTokenFromServer();
        //var_dump($accessToken);die();
        return $accessToken;
       
    }
    //授权返回页面
	public function callback()
	{
		$authorizationCode=  input('param.auth_code');
		$openPlatform = $this -> initialize();
		$authinfo = $openPlatform->getAuthorizationInfo($authorizationCode);
		$authinfo = $authinfo->authorization_info;
		$appid =  $authinfo['authorizer_appid'];  //appid
		$info = $openPlatform->getAuthorizerInfo($appid);
		$refreshtoken = $info['authorization_info']['authorizer_refresh_token'];
		$app = $openPlatform->createAuthorizerApplication($appid,$refreshtoken);
		
		//获取基本信息
		//标注： service_type_info ：1表示订阅号，2表示服务号，0表示小程序
		//verify_type_info ：-1表示未认证，0代表微信认证，1代表新浪微博认证，2代表腾讯微博认证，3代表已资质认证通过但还未通过名称认证，4代表已资质认证通过、还未通过名称认证，但通过了新浪微博认证，5代表已资质认证通过、还未通过名称认证，但通过了腾讯微博认证
		//首先判断一下这里是否是微信或者是小程序
		$type = $info['authorizer_info']['service_type_info']['id'];//用来判断是否是公众号和小程序
		$verifytype = $info['authorizer_info']['verify_type_info']['id'];//用来判断是否认证
		if($verifytype==0 or $verifytype==1 or $verifytype==2){
			$verifytype = 1;
		}else{
			$verifytype = 0;
		}
		if($type==2){//
			if(session('oid')){
				$wdata['oid'] = session('oid');
				$wdata['appid'] = $appid;
				$wdata['refreshtoken'] =  $info['authorization_info']['authorizer_refresh_token'];

				$wdata['authentication'] = $verifytype;
				$wdata['nick_name'] = $info['authorizer_info']['nick_name'];
				$wdata['create_user'] = session('id');
				$wdata['create_time'] = time();
				$wdata['is_delete'] = 1;
				//校验是否存在相同的appid如果有直接忽略，如果没有则添加
				$checked = Db::name('wechat_mp')->where(['appid'=>$appid,'is_delete'=>1,'oid'=>session('oid')])->find();
				
				if(!$checked){
					$checkedwechat = Db::name('wechat_mp')->where(['appid'=>$wdata['appid'],'is_delete'=>1])->where('oid','<>',session('oid'))->find();
					if($checkedwechat){
						die('您的微信公众号已经绑定过了!请更换一个试下');
					}
					Db::name('wechat_mp')->insert($wdata);
				}else{
					$checkedwechat = Db::name('wechat_mp')->where(['appid'=>$wdata['appid'],'is_delete'=>1])->where('oid','<>',session('oid'))->find();
					if($checkedwechat){
						die('您的微信公众号已经绑定过了!请更换一个试下');
					}
					Db::name('wechat_mp')->where('id',$checked['id'])->update($wdata);
				}
			}
		}elseif($type==0){
			if(session('oid')){

				$sdata['oid'] = session('oid');
				$sdata['appid'] = $info['authorization_info']['authorizer_appid'];
				$sdata['refreshtoken'] = $info['authorization_info']['authorizer_refresh_token'];
				$sdata['appname'] = $info['authorizer_info']['nick_name'];
				$sdata['authentication'] = $verifytype;
				$check = Db::name('smallapp')->where(['is_delete'=>1,'oid'=>session('oid')])->find();
				
				if(!$check){
					//Db::name('smallapp')->where(['oid'=>session('oid')])->update($sdata);
					die('您的操作有误,请联系技术');
				}else{
					$checkapp = Db::name('smallapp')->where('oid','<>',session('oid'))->where(['appid'=>$sdata['appid'],'is_delete'=>1])->find();
					if($checkapp){
						die('您的小程序已经绑定过了!请换一个再试!');
					}
					Db::name('smallapp')->where('id',$check['id'])->update($sdata);
					$smallapp = $app->smallapp;
					$result = Db::name('smallapp_serviceaddr')->where(['is_delete'=>1])->select();
					//初始化
					$requestdomain =array();
					$wsrequestdomain = array();
					$uploaddomain = array();
					$downloaddomain = array();
					$a=0;$b=0;$c=0;$d=0;
						foreach ($result as $k => $v) {
							if($v["types"]==1){
								$requestdomain[$a] = "https://".$v["addr"];
								$a ++;
							}elseif($v["types"]==2){
								$wsrequestdomain[$b] = "wss://".$v["addr"];
								$b ++;
							}elseif($v["types"]==3){
								$uploaddomain[$c] = 'https://'.$v["addr"];
								$c ++;
							}elseif($v["types"]==4){
								$downloaddomain[$d] = "https://".$v["addr"];
								$d ++;
							}

						}
					count($requestdomain)?'':$requestdomain=null;
					count($wsrequestdomain)?'':$wsrequestdomain=null;
					count($uploaddomain)?'':$uploaddomain=null;
					count($downloaddomain)?'':$downloaddomain[]=null;

					$domain = $smallapp->modify_domain('set',$requestdomain,$wsrequestdomain,$uploaddomain,$downloaddomain);
				}
			}
		}elseif($type==1){
			return $this->fetch();
		}
		if($type==0){
			//$this->assign('v',$authinfo);
			$this->redirect('/mlshare/Applet/index');
			//return $this->fetch();
		}else{
			$this->redirect('/mlshare/Wechat/index');
		}
		
	}
	//发送小程序模板消息
	public function sendtemplate($id,$data){
        $appid = Db::name('smallapp') -> where('oid',$id['oid']) -> field('appid,refreshtoken,return_template_id')->find();
		$openPlatform = $this -> initialize();
		$app = $openPlatform->createAuthorizerApplication($appid['appid'],$appid['refreshtoken']);
		$smallapp = $app->smallapp;
		$data = array(
			'keyword1' => array('value' => '￥ '.$data['real_amount']), 
			'keyword2' => array('value' => $data['order_no']), 
			'keyword3' => array('value' => $data['duration']), 
			'keyword4' => array('value' => date("Y年m月d日 H:i",$data['starttime'])), 
			'keyword5' => array('value' => date("Y年m月d日 H:i",$data['endtime'])), 
			'keyword6' => array('value' => '点击进入小程序查看详情和退还押金。','color'=>'#ff3300'), 
		);
		$page = 'pages/leaseorder/info?deposit=1&&id='.$id['orderid'];

       	$template = $smallapp->template_send($id['opneid'],$appid['return_template_id'],$id['formid'],$data,$page,null,'keyword1.DATA');

       	
       	if($template['errcode']==0){
       		//模板消息发送成功
       		save_log('../log/equipment',666);
			//save_log('../log/equipment',json_encode($template));
       	}else{
       		save_log('../log/equipment',777);
       	}
       

	}
	public function addr(){
		

		$appid = 'wx9b78f54f106368ff';
		$refreshtoken = 'refreshtoken@@@REzQAfExBbZjX9VxyvU9FN95YWOreg_CiVc3-1EkYps';
		$openPlatform = $this -> initialize();
		
		$app = $openPlatform->createAuthorizerApplication($appid,$refreshtoken);
		$smallapp = $app->smallapp;
		$result = Db::name('smallapp_serviceaddr')->where(['is_delete'=>1])->select();
		//初始化
		$requestdomain =array();
		$wsrequestdomain = array();
		$uploaddomain = array();
		$downloaddomain = array();
		$a=0;$b=0;$c=0;$d=0;
			foreach ($result as $k => $v) {
				if($v["types"]==1){
					$requestdomain[$a] = "https://".$v["addr"];
					$a ++;
				}elseif($v["types"]==2){
					$wsrequestdomain[$b] = "wss://".$v["addr"];
					$b ++;
				}elseif($v["types"]==3){
					$uploaddomain[$c] = 'https://'.$v["addr"];
					$c ++;
				}elseif($v["types"]==4){
					$downloaddomain[$d] = "https://".$v["addr"];
					$d ++;
				}

			}
		count($requestdomain)?'':$requestdomain=null;
		count($wsrequestdomain)?'':$wsrequestdomain=null;
		count($uploaddomain)?'':$uploaddomain=null;
		count($downloaddomain)?'':$downloaddomain[]=null;

		$domain = $smallapp->modify_domain('set',$requestdomain,$wsrequestdomain,$uploaddomain,$downloaddomain);
		var_dump($domain);
	}
	
	//获取VerifyTicke
    public function getVerifyTicket()
    {
        $openPlatform = $this -> initialize();
        $openPlatform->server->serve();
        echo('success');
    }
    //获取公众号返回消息
    public function getcallback()
    {

    	
    	
		$appid =input('param.appid');

    	$openPlatform = $this -> initialize();
		$server = $openPlatform->server;



		$server->setMessageHandler(function ($message) {
			switch ($message->MsgType) {
			    case 'event':  //收事件消息

			    	switch ($message['Event']) {
			    		case 'subscribe': //用户关注你


								

			    			//return "我是美味吗，你是谁？";
			    			break;

			    		case 'unsubscribe':  //取消关注
			    			# code...
			    			break;
			    		
			    		default:
			    			return $message['Event'].'from_callback';  //全完发布事件消息检测回复



			    			break;
			    	}

			    	echo('success');

			        die();
			        break;
			    case 'text':


			    	$Content = $message['Content'] ;
			    	
				    		if(strstr($Content, 'QUERY_AUTH_CODE:')){   //全完发布检测API文本消息回复

				    			$query_auth_code = substr($Content,16);
				    			$openPlatform = $this -> initialize();
								$authinfo = $openPlatform->getAuthorizationInfo($query_auth_code);

								$authinfo = json_encode($authinfo);
								$authinfo = json_decode($authinfo,true);

								$authinfo = $authinfo['authorization_info'];

								$appid =  $authinfo['authorizer_appid'];  //appid
								$refresh_token =  $authinfo['authorizer_refresh_token'];
								
								$app = $openPlatform->createAuthorizerApplication($appid,$refresh_token );
									
								$staff = $app->staff;
								$openId = $message['FromUserName'];
								$message = new Text(['content' => $query_auth_code.'_from_api']);

								$staff->message($message)->to($openId)->send();


								return;


				    		}
				    		if(strstr($Content, 'TESTCOMPONENT_MSG_TYPE_TEXT')){   //全网发布文本回复
			    				return "TESTCOMPONENT_MSG_TYPE_TEXT_callback";
			    			}


			    			/*if(strstr($Content, '客服消息')){

			    				$openPlatform = $this -> initialize();
			    				$info = $openPlatform->getAuthorizerInfo(input('param.appid'));


			    				$authinfo = $info->authorization_info;

								$appid =  $authinfo['authorizer_appid'];  //appid
									
								$refresh_token =  $authinfo['authorizer_refresh_token'];

								$app = $openPlatform->createAuthorizerApplication($appid,$refresh_token);
								$staff = $app->staff;
								$openId = $message['FromUserName'];
								$message = new Text(['content' => '您好，这是一条客服消息']);
								$staff->message($message)->by('kf2001@gh_8325d263708f')->to($openId)->send();
								return;
			    			}

				    		if(strstr($Content, '刘共经')){
			    				return "这个是我们的大BOSS。";
			    			}
				    		if(strstr($Content, '信哪儿')){
			    				return "深圳市信哪儿科技有限公司是一家很牛逼的公司";
			    			}
			    			if(strstr($Content, '开发')){
			    				return "要做开发找信哪儿就对了";
			    			}
			    			if(strstr($Content, '小程序')){
			    				return "做小程序找信哪儿";
			    			}
				    		if(strstr($Content, '人工服务')){
			    				return new Transfer();
			    			}else{

				    			return '听不懂，你如果急的话，可以输入"人工服务"来找美女客服。';
				    		}*/

			    		
			        break;
			    case 'image':
			        //return '收到图片消息';
			        break;
			    case 'voice':
			        //return '收到语音消息';
			        break;
			    case 'video':
			        //return '收到视频消息';
			        break;
			    case 'location':
			        //return '收到坐标消息';
			        break;
			    case 'link':
			        //return '收到链接消息';
			        break;
			        // ... 其它消息
			    default:
			        //return '收到其它消息';
			        break;
			}

		});
		$response = $server->serve();
		$response->send();




    }
}
